package com.hkts.naturalgas.login.Filter;

import com.hkts.naturalgas.login.cache.CacheVo;
import com.hkts.naturalgas.login.cache.LoginCacheUtils;
import com.hkts.naturalgas.login.config.CheckUrls;
import com.hkts.naturalgas.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @ClassNameLoginFilter
 * @Description
 * @Author yck
 * @Date2021-12-08 13:57
 * @Version V1.0
 **/

@Component
@Slf4j
public class LoginFilter implements Filter {
    @Autowired
    private CheckUrls checkUrls;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("登录过滤器初始化");
    }

    @Override
    public void destroy() {
        log.info("登录过滤器销毁");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse rep = (HttpServletResponse) servletResponse;
        rep.setHeader("Access-Control-Allow-Origin", "*"); //  这里最好明确的写允许的域名
        rep.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
        rep.setHeader("Access-Control-Max-Age", "3600");
        rep.setHeader("Access-Control-Allow-Headers", "Content-Type,accessToken,accesstoken,Authorization,ybg");
        String requestURI = req.getRequestURI();
        log.info("请求路径{}", requestURI);
        //Map<String, String[]> parameterMap = req.getParameterMap();
        if (checkUrls.getUrls().contains(requestURI)) {
            String accessToken = req.getHeader("accesstoken");
            CacheVo cacheVo = LoginCacheUtils.map.get(accessToken);
            if (cacheVo == null) {
                ResponseUtil.out(rep, ResponseUtil.resultMap(false, 401, "请先登录"));
                //rep.sendRedirect("/enviroment/unlogin");
            } else {
                //判断是否超时如果超时将原来的缓存删除
                Long timeStamp = cacheVo.getTimeStamp();
                Date dd = new Date();
                long time = dd.getTime();
                //设置超时时间30分钟
                if (time - timeStamp > 30 * 60 * 1000) {
                    LoginCacheUtils.map.remove(accessToken);
                    ResponseUtil.out(rep, ResponseUtil.resultMap(false, 401, "登录超时，请重新登录"));
                } else {
                    LoginCacheUtils.map.get(accessToken).setTimeStamp(time);
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }
}
